import 'dart:io';

import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
import 'package:path/path.dart' as path;

class DbManager {
  Database _database;

  Future<Database> get db async {
    _database = _database ?? await initDb();
    return _database;
  }

  // 初始化
  Future<DbManager> init() async {
    _database = await initDb();
    return this;
  }

  // 初始化数据库
  Future<Database> initDb() async {
    var dbsPath = await getDatabasesPath();
    var dbPath = path.join(dbsPath, "flutter.db");
    var exists = await databaseExists(dbPath);
    if (!exists) {
      try {
        await Directory(path.dirname(dbPath)).create(recursive: true);
        print("db 拷贝完成");
      } catch (_) {}

      ByteData data = await rootBundle.load(path.join("assets", "flutter.db"));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      await File(dbPath).writeAsBytes(bytes, flush: true);
    } else {
      print("db 已存在，无需拷贝");
    }
    return await openDatabase(dbPath, readOnly: false);
  }
}
